package homework.no_3;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * 3.使用DOM4J解析第1题 作业中编写的XML文档，输出所有学员信息，
 * 并进行以下操作：删除id为1的学生成绩信息，修改id为2的成绩为60，添加一个学生的成绩信息（id为5）。
 */
public class Dom4jTest {
    private static Document doc;
    private static final String PATH = "src/main/java/homework/no_3/Score3.xml";
    static{
        SAXReader reader = new SAXReader();
        try {
            doc = reader.read(new File(PATH));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    public static void showInfo(){
        Element root = doc.getRootElement();
        for(Iterator it = root.elementIterator();it.hasNext();){
            Element stu = (Element) it.next();
            System.out.println(stu.attributeValue("id"));
            for (Iterator chiNode = stu.elementIterator();chiNode.hasNext();){
                Element node = (Element)chiNode.next();
                System.out.println("\t"+node.getText());
            }
        }
    }
    public static void delete(){
        Element root = doc.getRootElement();
        List<Element> list = root.elements();
        Element soc = list.get(0).element("score");
        soc.getParent().remove(soc);
//        Element s = doc.getRootElement().element("student").element("score");
//        s.detach();

//        save(PATH);
    }

    public static void add(){
        Element root = doc.getRootElement();
        Element student = root.addElement("student");
        student.addAttribute("id","5");
        Element score = student.addElement("score");
        score.setText("999");
        save(PATH);
    }
    public static void update(){
        Element root = doc.getRootElement();
        List<Element> list = root.elements();
        //获得指定下标的节点然后修改属性
        Element score = list.get(1).element("score");
        score.setText("888");
        save(PATH);
    }
    public static void save(String path){
        OutputFormat format = OutputFormat.createPrettyPrint();
        try {
            XMLWriter writer = new XMLWriter(new FileWriter(path),format);
            writer.write(doc);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public static void main(String[] args) {

        delete();
        update();
        add();
        showInfo();
    }
}
